function out = convert_fg( segfn, fgfn, outfn, outfnseg )

seg = readSeg( segfn );
imwrite( uint8(seg), outfnseg );

bmap = seg2bmap(seg);
[cmap,cid2sid] = seg2cmap(seg,bmap);

FG = readbin(fgfn);

numContours = size(cid2sid,2);

out = 100*ones(size(cmap),'uint8');
for ci = 1:numContours
    abutSegs = cid2sid(:,ci);
    label = FG{2}(ci,:);
    if( label(1) == 1 || label(1)== -1 ) % encodes for F/G
        assert( label(1)==1 && label(2)==-1 || label(1)==-1 && label(2)==1 );
        fSeg = abutSegs( find( label== 1 ) );
        gSeg = abutSegs( find( label==-1 ) );
        out( seg==fSeg & cmap==ci ) = 255;
        out( seg==gSeg & cmap==ci ) = 0;
    else %doesn't encode for F/G
        out( cmap==ci ) = 200;
    end
end
imwrite( out, outfn );
%imshow(out);
 
% FG = readbin(infn);
% FG = FG{1};
% fprintf('fn = %s\n', infn);
% assert( isempty( find( FG~=0 & FG~=1 & FG~=-1 ) ) );
% FG(FG==0)=100;
% FG(FG==-1)=0;
% FG(FG==1)=255;
% FG = uint8(FG);
% imshow(FG);